import React, { useState, useEffect } from 'react';
import { Modal, Progress, Button, message } from 'antd';

const UpdateManager: React.FC = () => {
  const [updateAvailable, setUpdateAvailable] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState(0);
  const [updateDownloaded, setUpdateDownloaded] = useState(false);

  useEffect(() => {
    // 监听更新事件
    window.electronApi.ipcRenderer.on('update-available', () => {
      setUpdateAvailable(true);
    });

    window.electronApi.ipcRenderer.on('download-progress', (_,progress: any) => {
      console.log(progress);
      setDownloading(true);
      setDownloadProgress(progress.percent);
    });

    window.electronApi.ipcRenderer.on('update-downloaded', () => {
      setDownloading(false);
      setUpdateDownloaded(true);
    });

    window.electronApi.ipcRenderer.on('update-not-available', () => {
      message.info('当前已是最新版本');
    });

    window.electronApi.ipcRenderer.on('update-error', (_,error: any) => {
      message.error('更新失败: ' + (error.message || '未知错误'));
      setDownloading(false);
      setUpdateAvailable(false);
      setUpdateDownloaded(false);
    });

    // 组件加载后检查更新
    window.electronApi.ipcRenderer.send('check-update');

    return () => {
      // 清理事件监听
      window.electronApi.ipcRenderer.removeAllListeners('update-available');
      window.electronApi.ipcRenderer.removeAllListeners('download-progress');
      window.electronApi.ipcRenderer.removeAllListeners('update-downloaded');
      window.electronApi.ipcRenderer.removeAllListeners('update-not-available');
      window.electronApi.ipcRenderer.removeAllListeners('update-error');
    };
  }, []);

  const handleUpdate = () => {
    setUpdateAvailable(false);
    setDownloading(true);
    window.electronApi.ipcRenderer.send('update-app');
  };

  const handleFinish = () => {
    // 退出并安装更新已经在主进程中处理
    // 这里只是关闭对话框
    setUpdateDownloaded(false);
  };

  return (
    <>
      <Modal
        title="发现新版本"
        open={updateAvailable}
        closable={false}
        footer={[
          <Button key="update" type="primary" onClick={handleUpdate}>
            确认更新
          </Button>
        ]}
      >
        <p>发现新版本，请更新到最新版本以获得更好的体验。</p>
      </Modal>

      <Modal
        title="正在下载更新"
        open={downloading}
        closable={false}
        footer={null}
      >
        <Progress percent={parseFloat(downloadProgress.toFixed(2))} />
        <p>正在下载更新文件，请稍候... ({downloadProgress.toFixed(2)}%)</p>
      </Modal>

      <Modal
        title="更新下载完成"
        open={updateDownloaded}
        closable={false}
        footer={[
          <Button key="finish" type="primary" onClick={handleFinish}>
            完成
          </Button>
        ]}
      >
        <p>更新已下载完成，点击"完成"将自动重启应用并安装更新。</p>
      </Modal>
    </>
  );
};

export default UpdateManager;